import { useEffect, useRef, useState, useCallback } from 'react';
import { io, Socket } from 'socket.io-client';
import { useAuth } from './use-auth';

interface UseWebSocketOptions {
  url: string;
  onMessage?: (data: any) => void;
  onConnect?: () => void;
  onDisconnect?: () => void;
  onError?: (error: Error) => void;
}

export const useWebSocket = ({
  url,
  onMessage,
  onConnect,
  onDisconnect,
  onError,
}: UseWebSocketOptions) => {
  const socketRef = useRef<Socket | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const { token } = useAuth();

  useEffect(() => {
    if (!token) return;

    // 创建 WebSocket 连接
    socketRef.current = io(url, {
      auth: { token },
      autoConnect: true,
    });

    // 设置事件监听器
    socketRef.current.on('connect', () => {
      setIsConnected(true);
      onConnect?.();
    });

    socketRef.current.on('disconnect', () => {
      setIsConnected(false);
      onDisconnect?.();
    });

    socketRef.current.on('message', (data) => {
      onMessage?.(data);
    });

    socketRef.current.on('error', (error) => {
      onError?.(error);
    });

    // 清理函数
    return () => {
      if (socketRef.current) {
        socketRef.current.disconnect();
        socketRef.current = null;
      }
    };
  }, [url, token]);

  // 发送消息的函数
  const sendMessage = useCallback((event: string, data: any) => {
    if (socketRef.current && isConnected) {
      socketRef.current.emit(event, data);
    }
  }, [isConnected]);

  return {
    isConnected,
    sendMessage,
  };
}; 